
var ui = {
    appId: $("#appId").val(),//appid
    partnerId: $("#partnerId").val(),//商户号
    services: $("#services").val(),//支付类型
    amount: $("#amount"),//金额
    name: $("#name"),//名称
    phone: $("#phone"),//手机
    note: $("#note"),//备注
    errorMessage: $("#errorMessage").val(),
    payButton: $("#payButton"),
    backdrop: $("#backdrop"),
    fade: 0
}, reg_money = new RegExp("^(0|([1-9]{1}[0-9]{0,8}))(\.[0-9]{1,2})?$"), payObj = {}, orderNo = '';

/**
 * 关闭弹窗
 */
function closePopover() {
    //隐藏遮罩
    $("#backdrop").fadeOut(ui.fade, function () {
        $(this).removeClass("tpl-active");
    });
    //隐藏要素选项
    $(".tpl-popover").fadeOut(ui.fade, function () {
        $(this).removeClass("tpl-active");
    });
}

/**
 * 验证表单
 * @returns {boolean}
 */
function validation() {
    var result = true;
    var re = /^1(([3|5|7|8][\d]{9})|(47|45)[\d]{8})$/;

    if(!ui.amount.val()) {
        mui.toast("请输入支付金额");
        return false;
    }else if(!reg_money.test(ui.amount.val())) {
        mui.toast("支付金额格式不正确");
        return false;
    }else if(!ui.name.val()) {
        mui.toast("请输入姓名");
        return false;
    }else if(!re.test(ui.phone.val())) {
        mui.toast("请输入正确手机号");
        return false;
    }

    return result;
}


/**
 * 微信JSAPI调起
 */
function jsApiCall() {
    WeixinJSBridge.invoke(
    'getBrandWCPayRequest',
    payObj,
    function (res) {
        //支付成功
        if (res.err_msg == "get_brand_wcpay_request:ok") {
            window.location.href = "http://test.weixin2.mayi121.com/paysuccess?orderNo=" + orderNo;
        } else if (res.err_msg == "get_brand_wcpay_request:fail") { //支付失败
            mui.alert("支付失败", "温馨提示", "确定");
        } else if (res.err_msg == "get_brand_wcpay_request:cancel") { //支付过程中用户取消

        }
    });
}

/**
 * 调起支付
 */
function callPay() {
    if (typeof WeixinJSBridge == "undefined") {
        if (document.addEventListener) {
            document.addEventListener('WeixinJSBridgeReady', jsApiCall, false);
        } else if (document.attachEvent) {
            document.attachEvent('WeixinJSBridgeReady', jsApiCall);
            document.attachEvent('onWeixinJSBridgeReady', jsApiCall);
        }
    } else {
        jsApiCall();
    }
}


//获取url参数
function getParam(key){
    var params = location.href;
    params = params.split("?")[1];

    if(!params){
        return false;
    }

    params = params.split("&");
    for(k in params){
        var arr = params[k].split('=');
        if(arr[0] == key) {
            return arr[1];
        }
    }
}

$(function () {

    //mui.alert('3', "蚂蚁白领提示3", "确定");

    var openid = getParam('openid');
    var appid = getParam('appid');
    var partner_id = getParam('partner_id');
    var services = getParam('services');
    //mui.alert(partner_id, "蚂蚁白领提示1", "确定");
    //return false;

    if(services == '2'){
        $('#showPayType').text('微信');
    }else if(services == '5'){
        $('#showPayType').text('支付宝');
    }

    //错误提示
    if (!services) {
        mui.alert(ui.errorMessage, "蚂蚁白领提示", "确定");
    }

    //关闭弹框
    ui.backdrop.click(function () {
        closePopover();
    });

    //支付
    ui.payButton.click(function () {
        //验证
        if (validation()) {
            //表单参数
            var param = {
                appId: appid,
                partnerId: partner_id,
                services: services,
                amount: ui.amount.val(),
                name: ui.name.val(),
                phone: ui.phone.val(),
                note: ui.note.val(),
                openid:openid,
            };

            console.log(param);
            //return false;

            mui.showWaiting("正在下单");
            //统一下单
            $.ajax({
                type: "post",
                url: "http://test.weixin2.mayi121.com/api.pay",
                data: param,
                dataType: 'json',
                cache: false,
                timeout: 10000,//10秒
                success: function (back) {
                    mui.closeWaiting();
                    //console.log(back);

                    var dResult = back.result;

                    //是否成功
                    if (back.status == "2000") {
                        //订单编号
                        orderNo = dResult.erchantOrderNo;
                        //支付宝
                        if (param.services == "5") {
                            window.location.href = dResult.content;
                        } else if (param.services == "2") { //微信公众号
                            payObj = {
                                "appId": dResult.appId,         //公众号名称，由商户传入
                                "timeStamp": dResult.timeStamp, //时间戳，自1970年以来的秒数
                                "nonceStr": dResult.nonceStr, 	//随机串
                                "package": dResult.package,		//统一下单接口返回的prepay_id参数值，提交格式如：prepay_id=1234
                                "signType": dResult.signType,   //微信签名方式：
                                "paySign": dResult.paySign 		//微信签名
                            };

                            //调起支付
                            callPay();
                        }
                    } else {
                        if (param.services == '2') {
                            mui.alert("商户微信支付渠道升级中,请使用支付宝扫码支付,带来不便请谅解！", "蚂蚁白领提示", "确定");
                        } else {
                            mui.alert("商户支付宝支付渠道升级中,请使用微信扫码支付,带来不便请谅解！", "蚂蚁白领提示", "确定");
                        }
                    }
                },
                error: function (xhr, type, thrown) {
                    mui.closeWaiting();
                    if (type == "timeout") {
                        mui.alert("由于网络原因操作超时请刷新后重试", "蚂蚁白领提示", "确定");
                    } else {
                        mui.alert("下单出现错误请稍后再试", "蚂蚁白领提示", "确定");
                    }
                }
            });

        }

    });
});